/**
 * <p>filetreepanel的控制类</p>
 * 继承自Ext.app.Controller

 * @module Ext-ux-cceaf-controller
 * @class cceaf.controller.FileTreePanelCtrl
 * @extends Ext.app.Controller
 * @since 1.0
 */
Ext.define('cceaf.controller.FileTreePanelCtrl',{
	extend: 'Ext.app.Controller', 
	requires: [
	    
    ],
	
	
    constructor: function(config){
		config = config || {};
		
		config = Ext.applyIf(config || {}, {

		});

		cceaf.controller.FileTreePanelCtrl.superclass.constructor.apply(this, arguments);
	},

	/**
     * 监听事件
     */
    init: function() {
    	//控制层需控制视图的xtype
    	var controlledViewXType = this.controlledViewXType;
    	if (!controlledViewXType) {
    		//控制名称
    		var className = this.self.getName();
    		alert('必须设置控制层' + className + '需控制视图的xtype，即controlledViewXType属性！');
    		return;
    	}
    	/*
    	'itemclick':function(view,record,item,index,e){
    		if (record.data.leaf) {
    			this.page_edit();
    		} else {
    			if (config.rootId != record.data.id) {
    				this.page_edit();
    			}
    		}
    	}
    	*/
    	
    	//构建初始化的事件监听
    	var eventTemplate = "this.control({" + 
	    	"'aaaaa': {" +
	    	"	afterrender: this.initPage" +
	        "}," +
	        "'aaaaa': {" +
	    	"	itemcontextmenu: this.showContextMenu" +
	        "}," +
	        "'aaaaa': {" +
	    	"	itemclick: this.editItem" +
	        "}" +
    	"});";
	    
	    var eventString = eventTemplate.replace(/aaaaa/gi, controlledViewXType);
	    eval(eventString);
        
        this.registerEvent();
        
      //标记已经初始化完成
        this.isInit = true;
    },
    
    /**
     * 对于动态加载controller模式
     * 第一次加载后设置为true，再次加载后不在执行init方法 
     * 
     * @property isInit 
     * @type Boolean
     * @default false
     */
    isInit: false,
    
    /**
     * 监听其他事件
     */
    registerEvent: function(){
    	
    },
	
    /**
     * 显示右键点击树节点的
     */
    showContextMenu: function(view,record,item,index,e){
    	var controller = this;
    	var fileTreePanel = controller.getControlledView();

    	var fileContextMenu = new Ext.menu.Menu( {
			width: 100,
			items : [ {
				text : '查看' + fileTreePanel.moduleName,
				iconCls : 'page_viewIcon',
				handler : function() {
					controller.page_view();
				}
			}, {
				text : '修改' + fileTreePanel.moduleName,
				iconCls : 'page_editIcon',
				handler : function() {
					controller.page_edit();
				}
			}, {
				text : '删除' + fileTreePanel.moduleName,
				iconCls : 'page_deleteIcon',
				handler : function() {
					controller.page_delete();
				}
			}, {
				text : '重命名' + fileTreePanel.moduleName,
				iconCls : 'page_renameIcon',
				handler : function() {
					controller.page_rename();
				}
			}, {
				text : '下载' + fileTreePanel.moduleName,
				iconCls : 'downloadIcon',
				handler : function() {
					controller.page_download();
				}
			}]
		});
		
	    var dirContextMenu = new Ext.menu.Menu( {
			width: 100,
			items : [ {
				text : '新增' + fileTreePanel.moduleName,
				iconCls : 'page_addIcon',
				handler : function() {
					controller.page_add(true);
				}
			}, {
				xtype : 'menuseparator'
			}, {
				text : '新增子目录',
				iconCls : 'page_addIcon',
				handler : function() {
					controller.page_add(false);
				}
			}, {
				text : '删除目录',
				iconCls : 'page_deleteIcon',
				handler : function() {
					controller.page_delete();
				}
			}, {
				text : '重命名目录',
				iconCls : 'page_renameIcon',
				handler : function() {
					controller.page_rename();
				}
			}, {
				text : '上传' + fileTreePanel.moduleName,
				iconCls : 'uploadIcon',
				handler : function() {
					controller.page_upload();
				}
			}, {
				xtype : 'menuseparator'
			}, {
				text : '刷新目录',
				iconCls : 'page_refreshIcon',
				handler : function() {
					controller.getStore().load();
				}
			}]
		});
	    
	    var rootContextMenu = new Ext.menu.Menu( {
			width: 100,
			items : [ {
				text : '新增' + fileTreePanel.moduleName,
				iconCls : 'page_addIcon',
				handler : function() {
					controller.page_add(true);
				}
			}, {
				text : '新增子目录',
				iconCls : 'page_addIcon',
				handler : function() {
					controller.page_add(false);
				}
			}, {
				xtype : 'menuseparator'
			}, {
				text : '刷新目录',
				iconCls : 'page_refreshIcon',
				handler : function() {
					controller.getStore().load();
				}
			}]
		});
		
		
		e.preventDefault();

		//显示popmenu
		if (record.data.leaf) {
			fileContextMenu.showAt(e.getXY());
		} else {
			if (config.rootId == record.data.id) {
				rootContextMenu.showAt(e.getXY());
			} else {
				dirContextMenu.showAt(e.getXY());
			}
		}
    },
    
    /**
     * 单击树节点进行编辑
     */
    editItem: function(view,record,item,index,e){
    	var controller = this;
    	var fileTreePanel = controller.getControlledView();
    	
		if (record.data.leaf) {
			controller.page_edit();
		} else {
			if (fileTreePanel.rootId != record.data.id) {
				controller.page_edit();
			}
		}
	},
	
	/**
	 * 获取视图
	 *
     * @return {Ext.container.Container} 视图对象
     */
    getControlledView: function(){
    	var controlledViewXType = this.controlledViewXType;
    	var methodName = 'this.get' + controlledViewXType.substr(0,1).toUpperCase() + controlledViewXType.substring(1) + '()';
    	//alert(methodName);
    	
    	var view = eval(methodName);
    	return view;
    },
    
    /**
     * 新增对象
     */
    page_add: function(leaf){
    	var controller = this;
    	var fileTreePanel = controller.getControlledView();
    	var viewArea = fileTreePanel.up().down('viewArea'); 
    	
    	//设置页面状态为：新增页面
    	fileTreePanel.pageStatus = 'add';
    	var title = '新增' + fileTreePanel.moduleName;
    	
    	if(fileTreePanel.billForm == null){
    		fileTreePanel.createForm();
    	}
    	fileTreePanel.billForm.setTitle(title);
    	fileTreePanel.billForm.form.reset();
    	
    	if (leaf) {
    		var nodetype = fileTreePanel.billForm.down('#nodetype');
    		nodetype.setValue("0");
    		var remark = fileTreePanel.billForm.down('#remark');
    		remark.setReadOnly(false);
    	} else {
    		var nodetype = fileTreePanel.billForm.down('#nodetype');
    		nodetype.setValue("1");
    		var remark = fileTreePanel.billForm.down('#remark');
    		remark.setReadOnly(true);
    	}
    	var nodename = fileTreePanel.billForm.down('#nodename');
    	nodename.setReadOnly(false);
    	var btnSave = fileTreePanel.billForm.down('#btnSave');
    	btnSave.setVisible(true);
		
		//设置父节点值
		var selModel = fileTreePanel.getSelectionModel();
		var selectedCount = selModel.getCount();
    	if(selectedCount == 0){
    		cceaf.util.ExtHelper.showInfoDialog('请选择父节点');
    	}
    	else{
    		var nodeid = selModel.getLastSelected().get('id');
    		var nodename = selModel.getLastSelected().get('text');

    		var parentId = fileTreePanel.billForm.down('[name=' + fileTreePanel.parentId + ']');
    		if (parentId) {
    			parentId.setValue(nodeid);
        		parentId.setRawValue(nodename);
    		} 
    		
    		var parentName = fileTreePanel.billForm.down('[name=' + fileTreePanel.parentName + ']');
    		if (parentName) {
    			parentName.setValue(nodename);
    		}
    	}
    	
    	viewArea.add(fileTreePanel.billForm);
    	
    	//设置初始值
    	controller.initAddPage();
    },
    
    /**
     * 编辑对象
     */
    page_edit: function(){
    	var controller = this;
    	var fileTreePanel = controller.getControlledView();
    	var viewArea = fileTreePanel.up().down('viewArea'); 
    	
    	//设置页面状态为：编辑页面
    	fileTreePanel.pageStatus = 'edit';
    	var title = '编辑' + fileTreePanel.moduleName;
    	
    	var selModel = fileTreePanel.getSelectionModel();
   	 	var selectedCount = selModel.getCount();
    	if(selectedCount == 0){
    		cceaf.util.ExtHelper.showInfoDialog('请选择编辑的行');
    	}
    	else if(selectedCount > 1){
    		cceaf.util.ExtHelper.showInfoDialog('只能选择一行编辑');
    	}
    	else{
    		//得到编辑对象的主键
    		var masterkeys = fileTreePanel.masterKeyIds.split(',');
    		var url = fileTreePanel.findByKeyAction + '?';
    		var temp = selModel.getLastSelected().get('id');
    		url += masterkeys[0] + '=' + temp + '&';
    		url += 'nodename=' + selModel.getLastSelected().get('text') + '&';
    		url += 'leaf=' + selModel.getLastSelected().get('leaf') + '&';
			if(fileTreePanel.billForm == null){
	    		fileTreePanel.createForm();
	    	}
			fileTreePanel.billForm.form.reset();
			var btnSave = fileTreePanel.billForm.down('#btnSave');
    		var nodename = fileTreePanel.billForm.down('#nodename');
    		nodename.setReadOnly(true);
    		var remark = fileTreePanel.billForm.down('#remark');
    		
    		if (selModel.getLastSelected().get('leaf')) {
	    		remark.setReadOnly(false);
	    		btnSave.setVisible(true);
    		} else {
    			remark.setReadOnly(true);
    			btnSave.setVisible(false);
    		}
    		
    		viewArea.add(fileTreePanel.billForm);
    		alert(2);
        	//装载对象到表单
        	fileTreePanel.billForm.form.load({
		    	//url: queryGrid.findByKeyAction + '?' + queryGrid.masterKeyId + '=' + masterkey,
        		url: url,
		        waitMsg : '正在载入数据...',
		        success: function(form,action) { 
		        	//表单载入数据时,初始化其他操作
		        	fileTreePanel.initEditPage(action);
		        	
		        	//显示正确提示
		        	var jsonObject =eval("(" + action.response.responseText + ")");
		        	cceaf.util.ExtHelper.showInfoDialog(jsonObject.message);
		        },
		        failure: function(form,action) {
		        	//显示错误提示
		        	var jsonObject =eval("(" + action.response.responseText + ")");
		        	cceaf.util.ExtHelper.showErrorDialog(jsonObject.message);
		        }
		   	});
    	}
    },
    
    /**
     * 查看对象
     */
    page_view: function(){
    	var controller = this;
    	var fileTreePanel = controller.getControlledView();
    	var viewArea = fileTreePanel.up().down('viewArea'); 
    	
    	//设置页面状态为：编辑页面
    	fileTreePanel.pageStatus = 'view';
    	var title = '查看' + fileTreePanel.moduleName;
    	
    	var selModel = fileTreePanel.getSelectionModel();
   	 	var selectedCount = selModel.getCount();
    	if(selectedCount == 0){
    		cceaf.util.ExtHelper.showInfoDialog('请选择编辑的行');
    	}
    	else if(selectedCount > 1){
    		cceaf.util.ExtHelper.showInfoDialog('只能选择一行编辑');
    	}
    	else{
    		//得到编辑对象的主键
    		var masterkeys = fileTreePanel.masterKeyIds.split(',');
    		var url = fileTreePanel.findByKeyAction + '?';
    		var temp = selModel.getLastSelected().get('id');
    		url += masterkeys[0] + '=' + temp + '&';
    		url += 'nodename=' + selModel.getLastSelected().get('text') + '&';
    		url += 'leaf=' + selModel.getLastSelected().get('leaf') + '&';
			if(fileTreePanel.billForm == null){
	    		fileTreePanel.createForm();
	    	}
			fileTreePanel.billForm.form.reset();
			var btnSave = fileTreePanel.billForm.down('#btnSave');
    		btnSave.setVisible(false);
    		
    		var nodename = fileTreePanel.billForm.down('#nodename');
    		nodename.setReadOnly(true);
    		var remark = fileTreePanel.billForm.down('#remark');
    		if (selModel.getLastSelected().get('leaf')) {
	    		remark.setReadOnly(false);
    		} else {
    			remark.setReadOnly(true);
    		}
    		
    		viewArea.add(fileTreePanel.billForm);
    		
        	//装载对象到表单
        	fileTreePanel.billForm.form.load({
		    	//url: queryGrid.findByKeyAction + '?' + queryGrid.masterKeyId + '=' + masterkey,
        		url: url,
		        waitMsg : '正在载入数据...',
		        success: function(form,action) { 
		        	//表单载入数据时,初始化其他操作
		        	fileTreePanel.initEditPage(action);
		        	
		        	//显示正确提示
		        	var jsonObject =eval("(" + action.response.responseText + ")");
		        	cceaf.util.ExtHelper.showInfoDialog(jsonObject.message);
		        },
		        failure: function(form,action) {
		        	//显示错误提示
		        	var jsonObject =eval("(" + action.response.responseText + ")");
		        	cceaf.util.ExtHelper.showErrorDialog(jsonObject.message);
		        }
		   	});
    	}
    },
    
    /**
     * 删除对象
     */
    page_delete: function(){
    	var controller = this;
    	var fileTreePanel = controller.getControlledView();
    	var viewArea = fileTreePanel.up().down('viewArea'); 
    	
    	//获取要删除对象的主键集
    	var selModel = fileTreePanel.getSelectionModel();
    	var selectedCount = selModel.getCount();
    	if(selectedCount == 0){
    		cceaf.util.ExtHelper.showInfoDialog('请选择要删除的行');
    		return;
    	} else{
    		//确定要删除对象
    		Ext.MessageBox.show({
				title:'确认提示框',
				modal: true,
				msg: '此操作不能回退，确信要删除您选中的对象以及它的子对象吗？',
				minWidth: 200,
				buttons: Ext.MessageBox.YESNO,
				icon: Ext.MessageBox.QUESTION,
				fn:function(btn){
					if(btn == 'yes'){
						//得到删除对象的主键集
						var masterkeys = fileTreePanel.masterKeyIds.split(',');
						var params = {};
						var ids = "";
						for(var j=0;selModel.getSelection() != null && j<selModel.getSelection().length;j++){
				    		var selection = selModel.getSelection()[j];
				    		ids = ids + selection.get('id') + ",";
				    	}
						
			    		eval("params." + masterkeys[0] + "s = '" + ids + "';");
						
						//alert(params);
						
			    		Ext.MessageBox.wait('正在处理数据...', '提示'); //进度条等待
			    		Ext.Ajax.request({
			   				url: fileTreePanel.deleteAction,
			   				//params: { ids: ids },
			   				params: params,
			   				success: function(response){
			   					var isProcessSucess = cceaf.util.ExtHelper.processAjaxRequest(response,true);
			   					if(isProcessSucess){
			   						fileTreePanel.getStore().load();
			   						fileTreePanel.billForm.form.reset();
			   					}
			   				},
			   				failure: function(response){
			   					cceaf.util.ExtHelper.processAjaxRequest(response,false);
			   				}
						});
					}
				}
			});
    	}
    },
    
    /**
     * 重命名对象
     */
    page_rename: function(){
    	var controller = this;
    	var fileTreePanel = controller.getControlledView();
    	var viewArea = fileTreePanel.up().down('viewArea'); 
    	
    	//获取要删除对象的主键集
    	var selModel = fileTreePanel.getSelectionModel();
    	var selectedCount = selModel.getCount();
    	if(selectedCount == 0){
    		cceaf.util.ExtHelper.showInfoDialog('请选择要重命名的行');
    		return;
    	} else if(selectedCount > 1){
    		cceaf.util.ExtHelper.showInfoDialog('只能选择一行编辑');
    	} else{
    		var nodename = selModel.getLastSelected().get('text');
    		
    		//确定要重命名
    		Ext.MessageBox.prompt({
				title:'确认提示框',
				modal: true,
				msg: '此操作不能回退，确信要重命名您选中的对象吗？',
				minWidth: 200,
				buttons: Ext.MessageBox.YESNO,
				icon: Ext.MessageBox.QUESTION,
				prompt: true,
				value: nodename,
				fn:function(btn, text){
					if(btn == 'yes'){
						if (nodename == text) {
							cceaf.util.ExtHelper.showInfoDialog('重命名后的名称与原名称一致，请重新输入新的名称！');
							return;
						}
						//得到重命名对象的主键集
						var masterkeys = fileTreePanel.masterKeyIds.split(',');
						var params = {};
						var ids = "";
						for(var j=0;selModel.getSelection() != null && j<selModel.getSelection().length;j++){
				    		var selection = selModel.getSelection()[j];
				    		ids = ids + selection.get('id') + ",";
				    	}
						
			    		eval("params." + masterkeys[0] + " = '" + selModel.getLastSelected().get('id') + "';");
			    		eval("params.oldnodename = '" + nodename + "';");
			    		eval("params.newnodename = '" + text + "';");
						
			    		Ext.MessageBox.wait('正在处理数据...', '提示'); //进度条等待
			    		Ext.Ajax.request({
			   				url: fileTreePanel.renameAction,
			   				params: params,
			   				success: function(response){
			   					var isProcessSucess = cceaf.util.ExtHelper.processAjaxRequest(response,true);
			   					if(isProcessSucess){
			   						fileTreePanel.getStore().load();
			   					}
			   				},
			   				failure: function(response){
			   					cceaf.util.ExtHelper.processAjaxRequest(response,false);
			   				}
						});
					}
				}
			});
    	}
    },
    
    /**
     * 下载文件
     */
    page_download: function(){
    	var controller = this;
    	var fileTreePanel = controller.getControlledView();
    	var viewArea = fileTreePanel.up().down('viewArea'); 
    	
    	var url = fileTreePanel.downloadAction;
    	
    	//获取要删除对象的主键集
    	var selModel = fileTreePanel.getSelectionModel();
    	var selectedCount = selModel.getCount();
    	if(selectedCount == 0){
    		cceaf.util.ExtHelper.showInfoDialog('请选择要重命名的行');
    		return;
    	} else if(selectedCount > 1){
    		cceaf.util.ExtHelper.showInfoDialog('只能选择一行编辑');
    		return;
    	} else{
    		var nodeid = selModel.getLastSelected().get('id');
    		var nodename = selModel.getLastSelected().get('text');
    		url += '?nodeid=' + nodeid;
    		url += '&nodename=' + nodename;
    	}
    	
    	cceaf.util.CceafHelper.openUrl(url);
    },
    
    /**
     * 上传文件
     */
    page_upload: function(){
    	var controller = this;
    	var fileTreePanel = controller.getControlledView();
    	var viewArea = fileTreePanel.up().down('viewArea'); 
    	
    	var actionURL = fileTreePanel.uploadAction;
    	var selModel = fileTreePanel.getSelectionModel();
    	var nodeid = selModel.getLastSelected().get('id');
    	
    	var uploadForm = new Ext.form.Panel({
    		buttonAlign: 'center',
    		frame: true,
	        border: false,
	        bodyStyle: 'padding:5px 5px 0',
	        waitMsgTarget: true,
	        layout: 'anchor',
	        height: cceaf.util.ExtHelper.getBodyHeight(),
	        items: [
				{xtype: 'cceaflabel',html: '选择上传文件', anchor:'100%'},
				{
					xtype: 'filefield',
		            emptyText: '请选择文件...',			            
		            name: 'upload',
		            allowBlank: false,
		            buttonText: '上传',
		            buttonConfig: {
		                iconCls: 'uploadIcon'
		            },
		            anchor:'100%'
				},
	        	{xtype: 'hidden',name: 'nodeid', value: nodeid}
	        ],
	        buttons: [
  	        	{itemId:'btnUpload', text: '上传文件', pressed: true, iconCls: 'uploadIcon', 
  	        		handler: function(){
  	        			if(!uploadForm.form.isValid()){
  	        	    		return;
  	        	    	}
  	        			
  	        			uploadForm.form.submit({
	  	      	        	url: actionURL,
	  	      	        	waitMsg : '正在保存数据...',
	  	      	            success: function(from, action) { 
	  	      	            	cceaf.util.ExtHelper.showInfoDialog(action.result.message);
	  	      	            	
	  	      	            	//关闭窗口
	  	  	        	    	var win = uploadForm.findParentByType('window');
	  	  	        	    	if (win) {
	  	  	        	    		win.close();
	  	  	        	    	}
	  	  	        	    	
								//刷新树
	  	  	        	    	fileTreePanel.getStore().load();
	  	      	            },
	  	      	            failure: function(from, action) {
	  	      	            	if(action.result == null) return;
	  	      	            	cceaf.util.ExtHelper.showErrorDialog(action.result.message);   
	  	      	            }
	  	      	        });	
  	        		}
  	        	}
  	        ]
    	});
    	
    	new Ext.Window({
        	title: "上传文件",
        	modal: true,
        	width: 400,
        	height: 200,
        	autoScroll: true,
        	closeAction: 'hide',
        	layout: 'fit',
        	plain: true,
        	items: [uploadForm]
    	}).show();
    },
    
    /**
     * 页面载入时调用
     */
    initPage: function(){
//    	var fileTreePanel = this.getControlledView();
//    	if (!fileTreePanel) {
//    		cceaf.util.ExtHelper.showInfoDialog('controller必须实现getPanelView方法！');
//    		return;
//    	}
    },
    
    /**
     * 新增表单，设置初始值
     */
    initAddPage: function(){
    	
    },
    
    /**
     * 表单载入数据后,设置特殊值表单值
     */
    initEditPage: function(){
    	
    }
    
    
    
});